package com.gjp.activiti.helloworld;

import com.google.common.collect.Maps;
import org.activiti.engine.*;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.impl.form.DateFormType;
import org.activiti.engine.impl.form.StringFormType;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 启动类
 * <p>
 * Created by 郭金鹏 on 2018/6/19.
 */
public class DemoMain {

    public static void main(String[] args) throws ParseException {
        System.out.println("启动我们的程序");

        //创建流程引擎
        ProcessEngine processEngine = getProcessEngine();

        //部署流程定义文件
        ProcessDefinition processDefinition = getProcessDefinition(processEngine);

        //启动运行流程
        ProcessInstance processInstance = startProcess(processEngine, processDefinition);

        //处理流程任务
        handleTask(processEngine, processInstance);

        System.out.println("结束我们的程序");
    }

    /**
     * 处理流程任务
     * @param processEngine
     * @param processInstance
     * @throws ParseException
     */
    private static void handleTask(ProcessEngine processEngine, ProcessInstance processInstance) throws ParseException {
        Scanner scanner = new Scanner(System.in);
        //如果流程实例不为空，且没有结束
        while (processInstance != null && !processInstance.isEnded()) {
            //处理流程任务
            TaskService taskService = processEngine.getTaskService();
            //获取任务列表
            List<Task> list = taskService.createTaskQuery().list();
            System.out.println(String.format("待处理任务数量{ %s }", list.size()));
            for (Task task : list) {
                System.out.println(String.format("待处理任务{ %s }", task.getName()));
                //获取表单数据
                Map<String, Object> variables = getStringObjectMap(processEngine, scanner, task);
                //提交流程
                taskService.complete(task.getId(), variables);
                //获取流程实例最新状态
                processInstance = processEngine.getRuntimeService()
                        .createProcessInstanceQuery()
                        .processInstanceId(processInstance.getId())
                        .singleResult();
            }
        }
        scanner.close();
    }

    /**
     * 获取表单数据
     * @param processEngine
     * @param scanner
     * @param task
     * @return
     * @throws ParseException
     */
    private static Map<String, Object> getStringObjectMap(ProcessEngine processEngine, Scanner scanner, Task task) throws ParseException {
        FormService formService = processEngine.getFormService();
        TaskFormData taskFormData = formService.getTaskFormData(task.getId());
        List<FormProperty> formProperties = taskFormData.getFormProperties();
        //输出表单key value
        for (FormProperty formProperty : formProperties) {
            System.out.println(formProperty.getId()+":"+formProperty.getValue());
        }
        //表单数据
        Map<String, Object> variables = Maps.newHashMap();
        //循环输入数据
        for (FormProperty formProperty : formProperties) {
            String line = "";
            //判断数据类型
            if (StringFormType.class.isInstance(formProperty.getType())) {
                //字符串类型
                System.out.println(String.format("请输入 { %s }", formProperty.getName()));
                line = scanner.nextLine();
                variables.put(formProperty.getId(), line);
            } else if (DateFormType.class.isInstance(formProperty.getType())) {
                //日期类型
                System.out.println(String.format("请输入 { %s } , 格式(yyyy-MM-dd)", formProperty.getName()));
                line = scanner.nextLine();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sdf.parse(line);
                variables.put(formProperty.getId(), date);
            } else {
                //其他类型
                System.out.println(String.format("{ %s } 类型暂不支持", formProperty.getType()));
            }
            System.out.println(String.format("您输入的内容是：{ %s }", line));
        }
        return variables;
    }


    /**
     * 启动流程
     * @param processEngine
     * @param processDefinition
     * @return
     */
    private static ProcessInstance startProcess(ProcessEngine processEngine, ProcessDefinition processDefinition) {
        ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceById(processDefinition.getId());
        System.out.println(String.format("启动流程{ %s }", processInstance.getProcessDefinitionKey()));
        return processInstance;
    }

    /**
     * 部署流程定义
     * @param processEngine
     * @return
     */
    private static ProcessDefinition getProcessDefinition(ProcessEngine processEngine) {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        Deployment deploy = deploymentBuilder
                .addClasspathResource("second_approve.bpmn20.xml")
                .deploy();
        String deployId = deploy.getId();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployId)
                .singleResult();
        System.out.println(String.format("流程定义文件{ %s }，流程id{ %s }", processDefinition.getName(), processDefinition.getId()));
        return processDefinition;
    }

    /**
     * 创建流程引擎
     * @return
     */
    private static ProcessEngine getProcessEngine() {
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
        ProcessEngine processEngine = cfg.buildProcessEngine();
        String processEngineName = processEngine.getName();
        String version = ProcessEngine.VERSION;
        System.out.println(String.format("流程引擎名称{ %s },版本{ %s }", processEngineName, version));
        return processEngine;
    }
}
